package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseFinishVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;


/**
 * @author lihaojie
 */
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    
    @Autowired
    PurchaseDetailService detailService;
    
    @Autowired
    WareSkuService wareSkuService;
    
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );
        
        return new PageUtils(page);
    }
    
    /**
     * 获取未领取的采购单
     */
    @Override
    public PageUtils getPurchasePageList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .eq("status", WareConstant.PurchaseEnum.CREATED.getCode())
                        .or()
                        .eq("status", WareConstant.PurchaseEnum.ASSIGNED.getCode())
        );
        return new PageUtils(page);
    }
    
    /**
     * 合并采购需求
     */
    @Override
    public R purchaseMerge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        //标记是否是新建采购单
        boolean isFlag = true;
        //如果采购单不存在则自动创建一个采购单
        if (ObjectUtils.isEmpty(purchaseId)) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
            isFlag = false;
        }
    
        if (isFlag) {
            //校验购物单是否已经被领取
            PurchaseEntity purchase = this.getById(purchaseId);
            if (purchase.getStatus() == WareConstant.PurchaseEnum.RECEIVE.getCode() || purchase.getStatus() == WareConstant.PurchaseEnum.FINISH.getCode() || purchase.getStatus() == WareConstant.PurchaseEnum.HASERROR.getCode()) {
                return R.error("当前状态不能改变");
            }
        }
    
        //修改采购需求信息
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntityList = mergeVo.getItems().stream().map(item -> {
            PurchaseDetailEntity purchaseDetail = detailService.getById(item);
            if (purchaseDetail.getStatus() == WareConstant.PurchaseEnum.RECEIVE.getCode() || purchaseDetail.getStatus() == WareConstant.PurchaseEnum.FINISH.getCode() || purchaseDetail.getStatus() == WareConstant.PurchaseEnum.HASERROR.getCode()) {
                return null;
            }
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).filter(item -> item != null).collect(Collectors.toList());
        detailService.updateBatchById(purchaseDetailEntityList);
        
        
        if (isFlag) {
            //更新采购单时间
            if (!CollectionUtils.isEmpty(purchaseDetailEntityList)) {
                PurchaseEntity purchaseEntity = new PurchaseEntity();
                purchaseEntity.setId(purchaseId);
                purchaseEntity.setUpdateTime(new Date());
                this.updateById(purchaseEntity);
            }
        }
        return R.ok();
    }
    
    /**
     * 领取采购单
     */
    @Override
    public void purchaseReceived(List<Long> ids) {
        //1、获取采购单
        List<PurchaseEntity> purchaseEntityList = ids.stream().map(purchaseId -> {
            PurchaseEntity purchaseEntity = this.getById(purchaseId);
            return purchaseEntity;
        }).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseEnum.CREATED.getCode()
                    || item.getStatus() == WareConstant.PurchaseEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item -> {
            item.setUpdateTime(new Date());
            item.setStatus(WareConstant.PurchaseEnum.RECEIVE.getCode());
            return item;
        }).collect(Collectors.toList());
        
        if (!CollectionUtils.isEmpty(purchaseEntityList)) {
            return;
        }
        
        //2、修改采购单
        this.updateBatchById(purchaseEntityList);
        
        //3、修改采购项
        purchaseEntityList.forEach(item -> {
            List<PurchaseDetailEntity> purchaseDetailEntities = detailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> detailEntityList = purchaseDetailEntities.stream().map(purchaseDetailEntity -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(purchaseDetailEntity.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.PROCURING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            this.detailService.updateBatchById(detailEntityList);
        });
        
    }
    
    /**
     * 完成采购
     */
    @Override
    public void purchaseFinish(PurchaseFinishVo purchaseFinishVo) {
        //购物单Id
        Long id = purchaseFinishVo.getId();
        
        //1、更新购物单状态
        
        //2、更新购物项状态
        AtomicBoolean isFlag = new AtomicBoolean(true);
        List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseFinishVo.getItems().stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                isFlag.set(false);
                purchaseDetailEntity.setStatus(item.getStatus());
            } else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
            }
            purchaseDetailEntity.setId(item.getItemId());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
    
        detailService.updateBatchById(purchaseDetailEntityList);
        
        //更新购物单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(isFlag.get() ? WareConstant.PurchaseEnum.FINISH.getCode() : WareConstant.PurchaseEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);
        //3、修改库存
        purchaseDetailEntityList.forEach(item -> {
            PurchaseDetailEntity purchaseDetail = detailService.getById(item.getId());
            if (purchaseDetail == null) {
                return;
            }
            wareSkuService.addStock(purchaseDetail.getSkuId(), purchaseDetail.getWareId(), purchaseDetail.getSkuNum());
        });
        
        
    }
    
    
}